package com.vframework.common.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.util.StringUtil;
import com.util.UploadUtil;
import com.vframework.base.controller.BaseController;
import com.vframework.common.constant.BusinessConstant;

/***************************************************************
 * Name:        FileLoadAction.java
 * Create At:   2010-04-22
 * Module:      文件下载公用action
 * Description: [参数： FILEID 要下载的id DOWNLOAD 是否弹出另存窗口，1=另存、否则直接输出到页面 处理附件下载]
 * Author       
 * ------------------------------------------------------------
 * 修改历史
 * 序号  日期  修改人   修改原因
 * 1
 * 2
***************************************************************/
@Controller
@RequestMapping("UploadFileController")
public class UploadFileController extends BaseController {
    /**
     * @author   shanzhitong
     * @param    request
     * @return    Map
     * @description  图片上传同时删除旧图片
     */
    @RequestMapping("upload")
    @ResponseBody
    @SuppressWarnings("unchecked")
	public Map upload(HttpServletRequest request) {
        String fileSubDir = request.getParameter("fileSubDir");
		if(!StringUtil.isEmpty(fileSubDir) && fileSubDir.startsWith(BusinessConstant.FILE_STORE_PREFIX)) {
		    fileSubDir = fileSubDir.split(BusinessConstant.ATTACHMENT_DIR)[1].substring(1);
		}
		String oldPath = request.getParameter("oldPath");
		if (!StringUtil.isEmpty(oldPath)) {
		    UploadUtil.deleteFile(oldPath);
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("file");// 获取上传文件
		Map uploadRes = UploadUtil.upload(multipartFile, multipartFile.getOriginalFilename(),fileSubDir, request.getParameter("permission"));
		String fileUrlShow = UploadUtil.replacePath((String) uploadRes.get("path"));
		uploadRes.put("result", "SUCCESS");
		uploadRes.put("pathShow", fileUrlShow);
		return uploadRes;
	}

    /**
     * @author   shanzhitong
     * @param    request
     * @return    Map
     * @description  删除图片
     */
    @RequestMapping("delete")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Map delete(HttpServletRequest request) {
        Map deleteResult = new HashMap();
        String path = request.getParameter("path");
        if(StringUtil.isEmpty(path)){
            deleteResult.put("result", "FAIL");
            deleteResult.put("message", "路径为空，删除失败！");
            return deleteResult;
        }
        UploadUtil.deleteFile(path);
        deleteResult.put("result", "SUCCESS");
        deleteResult.put("message", "文件删除成功！");
        return deleteResult;
    }
}